/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.z100h.supplychain.order.web;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.z100h.supplychain.evidence.facade.StockOutSpecialFacade;
import com.z100h.supplychain.order.entity.Order;
import com.z100h.supplychain.order.entity.OrderCustomer;
import com.z100h.supplychain.order.entity.OrderDetailVo;
import com.z100h.supplychain.order.entity.OrderSpec;
import com.z100h.supplychain.order.entity.OrderVo;
import com.z100h.supplychain.order.facade.OrderFacade;
import com.z100h.supplychain.order.service.OrderService;

/**
 * 订单Controller
 * @author fyh
 * @version 2019-04-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sc/order/order")
public class OrderController extends BaseController {

	@Autowired
	private OrderService orderService;

	@Autowired
	private OrderFacade orderFacade;

	@Autowired
	private StockOutSpecialFacade stockOutSpecialFacade;

	@ModelAttribute
	public Order get(@RequestParam(required = false) String id) {
		Order entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = orderService.get(id);
		}
		if (entity == null) {
			entity = new Order();
		}
		return entity;
	}

	/**
	 * 订单列表页面
	 */
	@RequiresPermissions("sc:order:order:list")
	@RequestMapping(value = { "list", "" })
	public String list() {
		return "supplychain/order/orderList";
	}

	@RequestMapping(value = "nullInNullOutList")
	public String nullInNullOutList() {
		return "supplychain/order/nullInNullOut";
	}

	/**
	* 订单列表数据
	*/
	@ResponseBody
	// @RequiresPermissions("sc:order:order:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data(Order order, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<Order> page = orderService.findPage(new Page<Order>(request, response), order);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑订单表单页面
	 */
	// @RequiresPermissions(value={"sc:order:order:view","sc:order:order:add","sc:order:order:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Order order, Model model) {
		model.addAttribute("order", order);
		if (StringUtils.isBlank(order.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "supplychain/order/orderForm";
	}

	/**
	 * 保存订单
	 */
	@RequiresPermissions(value = { "sc:order:order:add", "sc:order:order:edit" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(Order order, Model model, RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, order)) {
			return form(order, model);
		}
		// 新增或编辑表单保存
		orderService.save(order);// 保存
		addMessage(redirectAttributes, "保存订单成功");
		return "redirect:" + Global.getAdminPath() + "/sc/order/order/?repage";
	}

	/**
	 * 删除订单
	 */
	@ResponseBody
	@RequiresPermissions("sc:order:order:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Order order, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		orderService.delete(order);
		j.setMsg("删除订单成功");
		return j;
	}

	/**
	 * 批量删除订单
	 */
	@ResponseBody
	@RequiresPermissions("sc:order:order:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			orderService.delete(orderService.get(id));
		}
		j.setMsg("删除订单成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sc:order:order:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(Order order, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "订单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Order> page = orderService.findPage(new Page<Order>(request, response, -1), order);
			new ExportExcel("订单", Order.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出订单记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据
	
	 */
	@RequiresPermissions("sc:order:order:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Order> list = ei.getDataList(Order.class);
			for (Order order : list) {
				try {
					orderService.save(order);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条订单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条订单记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入订单失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sc/order/order/?repage";
	}

	/**
	 * 下载导入订单数据模板
	 */
	@RequiresPermissions("sc:order:order:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "订单数据导入模板.xlsx";
			List<Order> list = Lists.newArrayList();
			new ExportExcel("订单数据", Order.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sc/order/order/?repage";
	}

	@RequestMapping(value = "orderDetail")
	public String orderDetail(HttpServletRequest request, String orderId) {
		request.setAttribute("orderId", orderId);
		return "supplychain/page/orderDetail";
	}

	@ResponseBody
	@RequestMapping(value = "findOrderCustomerByOrderId")
	public OrderCustomer findOrderCustomerByOrderId(String orderId) {
		return orderFacade.getOrderCustomerByOrderId(orderId);
	}

	/**
	 * 
	 * 出库工艺单导出
	 * 
	 * @param response
	 * @param stockoutId
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2019年4月18日 上午10:26:52
	 */
	@RequestMapping(value = "exportExcel")
	public void exportExcel(HttpServletResponse response, String stockoutId) {
		try {
			Workbook workbook = orderFacade.createStockoutWorkBook(stockoutId);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime() + ".xls");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "exportRepairExcel")
	public void exportRepairExcel(HttpServletResponse response, String stockoutId) {
		try {
			Workbook workbook = orderFacade.createRepairStockoutWorkBook(stockoutId);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime() + ".xls");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "exportExcelAll")
	public void exportExcelAll(HttpServletResponse response, String stockoutIds, String isSupplement) {
		String[] arr = stockoutIds.split(",");
		List<String> stockoutIdList = Arrays.asList(arr);
		try {
			Workbook workbook = orderFacade.createWorkbookByEvidenceIds(stockoutIdList, isSupplement);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime() + ".xls");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "exportExcelAllNew")
	public void exportExcelAllNew(HttpServletResponse response, String stockoutIds, String isSupplement) {
		String[] arr = stockoutIds.split(",");
		List<String> stockoutIdList = Arrays.asList(arr);
		try {
			Workbook workbook = orderFacade.createWorkbookByEvidenceIdsNew(stockoutIdList, isSupplement);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime() + ".xlsx");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * 下载打码
	 * 
	 * @param response
	 * @param evidenceId
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2019年10月10日 上午9:50:33
	 */
	@RequestMapping(value = "exportCode")
	public void exportCode(HttpServletResponse response, String evidenceId) {
		try {
			Workbook workbook = orderFacade.exportCode(evidenceId);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime() + ".xls");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = { "listOfProduce", "" })
	public String listOfProduce(HttpServletRequest request, String customerId) {
		request.setAttribute("customerId", customerId);
		return "supplychain/order/listOfProduce";
	}

	/**
	 * 
	 * 订单详情
	 * 
	 * @param orderId
	 * @return
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2019年9月23日 下午3:07:43
	 */
	@ResponseBody
	@RequestMapping(value = "findOrderDetail")
	public OrderDetailVo findOrderDetail(String orderId) {
		return orderFacade.findOrderDetail(orderId);
	}

	@RequestMapping(value = { "repairDetailList", "" })
	public String repairDetailList(HttpServletRequest request, String customerId) {
		request.setAttribute("customerId", customerId);
		return "supplychain/order/listOfRepair";
	}

	@RequestMapping(value = "findRepairByCustomerId")
	@ResponseBody
	public Map<String, Object> findRepairByCustomerId(HttpServletRequest request, HttpServletResponse response,
			String customerId) {
		Page<OrderSpec> page = new Page<OrderSpec>(request, response);
		// List<OrderSpec> list = orderFacade.findRepairByCustomerId(customerId);
		List<OrderSpec> list = orderFacade.findRepairSkuByCustomerId(customerId);
		page.setList(list);
		return getBootstrapData(page);
	}

	@RequestMapping(value = { "orderSummary", "" })
	public String orderSummary(HttpServletRequest request, String customerId) {
		request.setAttribute("customerId", customerId);
		return "supplychain/order/orderSummary";
	}

	@RequestMapping(value = "findOrderDetailByCustomerId")
	@ResponseBody
	public Map<String, Object> findOrderDetailByCustomerId(HttpServletRequest request, HttpServletResponse response,
			String customerId) {
		Page<OrderSpec> page = new Page<OrderSpec>(request, response);
		// List<OrderSpec> list = orderFacade.findOrderDetailByCustomerId(customerId);
		List<OrderSpec> list = orderFacade.findOrderDetailSkuByCustomerId(customerId);
		page.setList(list);
		return getBootstrapData(page);
	}

	@RequestMapping(value = { "summary", "" })
	public String summary(HttpServletRequest request, String customerId) {
		request.setAttribute("customerId", customerId);
		return "supplychain/order/summary";
	}

	@RequestMapping(value = "findSummaryByCustomerId")
	@ResponseBody
	public Map<String, Object> findSummaryByCustomerId(HttpServletRequest request, HttpServletResponse response,
			String customerId) {
		Page<OrderSpec> page = new Page<OrderSpec>(request, response);
		// List<OrderSpec> list = orderFacade.findSummaryByCustomerId(customerId);
		List<OrderSpec> list = orderFacade.findSummarySkuByCustomerId(customerId);
		page.setList(list);
		return getBootstrapData(page);
	}

	@RequestMapping(value = "findCustomerDetail")
	@ResponseBody
	public Map<String, Object> findCustomerDetail(HttpServletRequest request, HttpServletResponse response,
			String customerId, String serviceType) {
		Page<OrderSpec> page = new Page<OrderSpec>(request, response);
		List<OrderSpec> list = orderFacade.findCustomerDetail(customerId, serviceType);
		page.setList(list);
		return getBootstrapData(page);
	}

	/**
	 * 
	 * 批量下载打码
	 * 
	 * @param response
	 * @param stockoutIds
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2019年10月17日 上午9:52:58
	 */
	@RequestMapping(value = "exportAllCode")
	public void exportAllCode(HttpServletResponse response, String evidenceIds) {
		String[] arr = evidenceIds.split(",");
		List<String> list = Arrays.asList(arr);
		try {
			Workbook workbook = orderFacade.exportExcelAllCode(list);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + "barcode_qrcode" + ".xlsx");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "exportAllCodeV2")
	public void exportExcelAllCodeByOrderIds(HttpServletResponse response, String orderIds) {
		String[] arr = orderIds.split(",");
		List<String> list = Arrays.asList(arr);
		try {
			Workbook workbook = orderFacade.exportExcelAllCodeByOrderIds(list);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + "barcode_qrcode" + ".xlsx");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@ResponseBody
	@RequestMapping(value = "nullINNullOut")
	public String nullINNullOut(String erpOrderId, BigDecimal purchaseOrderPrice) {
		try {
			stockOutSpecialFacade.nullInNullOut(erpOrderId, purchaseOrderPrice);
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@ResponseBody
	// @RequiresPermissions("sc:order:order:findByPage")
	@RequestMapping(value = "data")
	public Map<String, Object> findByPage(Page<OrderVo> page, OrderVo orderVo, HttpServletRequest request,
			HttpServletResponse response) {
		orderVo.setCompanyId(UserUtils.getUser().getCompanyId());

		page = orderFacade.findByPage(page, orderVo);
		return getBootstrapData(page);
	}

}